package com.wqz.taco_cloud_jpa.controller;

import com.wqz.taco_cloud_jpa.impl.OrderRepository;
import com.wqz.taco_cloud_jpa.models.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.validation.Valid;

@Slf4j
@Controller
@RequestMapping("/order")
@SessionAttributes("order")
public class OrderController {
    private final OrderRepository orderRepository;

    @Autowired
    public OrderController(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    /**
     * 对于current的路径请求
     * @param model
     * @return
     */
    @GetMapping("/current")
    public String OrderForm(Model model) {
        model.addAttribute("order", new Order());
        log.info("enter order view");
        return "orderForm";
    }

    /**
     * 对于/orders的post请求的处理
     * 对于提交的表单需要进行是否是合法输入的校验
     * 添加校验的方式可以在processOrder方法中或者在model中的Order类中添加校验，后者可读性更高
     * 在model添加校验后，需要在post方法中添加@Valid注解，告诉Controller需要进行校验
     * @param order
     * @param errors
     * @param sessionStatus
     * @return
     */
    @PostMapping("/order")
    public String processOrder(@Valid Order order, Errors errors, SessionStatus sessionStatus) {
        if (errors.hasErrors()) {
            log.info("errors occurred and it is " + errors.toString());
            return "orderForm";
        }
        // 这里点击submit的button后居然没法执行到这里,原因是没有explicit mapping
        log.info("submit order process---->end");
        orderRepository.save(order);
        sessionStatus.setComplete();
        log.info("Order submitted: " + order);
        // 重定向到home
        return "redirect:/";
    }
}
